{/* Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs';
export default Layout;

import docs from 'docs:@react-spectrum/searchfield';
import {HeaderInfo, PropTable, PageDescription} from '@react-spectrum/docs';
import packageData from '@react-spectrum/searchfield/package.json';

```jsx import
import {Flex} from '@react-spectrum/layout';
import {SearchField} from '@react-spectrum/searchfield';
import User from '@spectrum-icons/workflow/User';
```

---
category: Forms
keywords: [search field, input]
---

# SearchField

<PageDescription>{docs.exports.SearchField.description}</PageDescription>

<HeaderInfo
  packageData={packageData}
  componentNames={['SearchField']}
  sourceData={[
  {type: 'Spectrum', url: 'https://spectrum.adobe.com/page/search-field/'}
  ]}
  since="3.0.0" />

## Example

```tsx example
function Example() {
  let [submittedText, setSubmittedText] = React.useState(null);

  return (
    <>
      <SearchField
        label="Search"
        onSubmit={setSubmittedText} />
      <p>Submitted text: {submittedText}</p>
    </>
  );
}
```

## Value

A SearchField's `value` is empty by default, but an initial, uncontrolled, value can be provided using the `defaultValue` prop.
Alternatively, a controlled value can be provided using the `value` prop.

```tsx example
function Example() {
  let [searchValue, setSearchValue] = React.useState('puppies');
  return (
    <Flex gap="size-300">
      <SearchField
        defaultValue="puppies"
        label="Search (uncontrolled)" />

      <SearchField
        value={searchValue}
        onChange={setSearchValue}
        label="Search (controlled)" />
    </Flex>
  );
}
```

### HTML forms

SearchField supports the `name` prop for integration with HTML forms. In addition, attributes such as `type`, `pattern`, `inputMode`, and others are passed through to the underlying `<input>` element.

```tsx example
<SearchField label="Email" name="email" type="email" />
```

## Labeling

A visual label should be provided for the SearchField using the `label` prop. If the SearchField is required, the `isRequired` and `necessityIndicator` props can be used to show a required state.

```tsx example
<Flex gap="size-300" wrap>
  <SearchField label="Search" />
  <SearchField label="Search" isRequired necessityIndicator="icon" />
  <SearchField label="Search" isRequired necessityIndicator="label" />
  <SearchField label="Search" necessityIndicator="label" />
</Flex>
```

### Accessibility

If a visible label isn't specified, an `aria-label` must be provided to the SearchField for
accessibility. If the field is labeled by a separate element, an `aria-labelledby` prop must be provided using
the `id` of the labeling element instead.

### Internationalization

In order to internationalize a SearchField, a localized string should be passed to the `label` or `aria-label` prop.
When the `necessityIndicator` prop is set to `"label"`, a localized string will be provided for `"(required)"` or `"(optional)"` automatically.

## Events

The most commonly used handlers for events in SearchField are the:
- `onChange` prop which is triggered whenever the value is edited by the user.
- `onSubmit` prop which is triggered whenever the value is submitted by the user.
- `onClear` prop which is triggered whenever the value is cleared by the user.

The example below uses `onChange`, `onSubmit`, and `onClear` to update two separate elements with the text entered into the SearchField.

```tsx example
function Example() {
  let [currentText, setCurrentText] = React.useState('');
  let [submittedText, setSubmittedText] = React.useState('');

  return (
    <div>
      <SearchField
        onClear={() => setCurrentText('')}
        onChange={setCurrentText}
        onSubmit={setSubmittedText}
        label="Your text"
        value={currentText}
      />
      <pre>Mirrored text: {currentText}</pre>
      <pre>Submitted text: {submittedText}</pre>
    </div>
  );
}
```

## Validation

SearchField supports native HTML [constraint validation](https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation) props such as `isRequired`, `minLength`, and `pattern`, as well as custom validation functions, realtime validation, and server-side validation. It can also be integrated with other form libraries. See the [Forms](forms.html) guide to learn more.

When the [Form](Form.html) component has the `validationBehavior="native"` prop, validation errors block form submission and are displayed as help text automatically. Errors are displayed when the user blurs the search field or submits the form.

```tsx example
import {Form, ButtonGroup, Button} from '@adobe/react-spectrum';

<Form validationBehavior="native" maxWidth="size-3000">
  {/*- begin highlight -*/}
  <SearchField label="Search" name="search" isRequired />
  {/*- end highlight -*/}
  <ButtonGroup>
    <Button type="submit" variant="primary">Submit</Button>
    <Button type="reset" variant="secondary">Reset</Button>
  </ButtonGroup>
</Form>
```

By default, `SearchField` displays default validation messages provided by the browser. See [Customizing error messages](forms.html#customizing-error-messages) in the Forms guide to learn how to provide your own custom errors.

## Props

<PropTable component={docs.exports.SearchField} links={docs.links} />

## Visual options

### Quiet

```tsx example
<SearchField label="Search" isQuiet />
```

### Disabled

```tsx example
<SearchField label="Search" isDisabled />
```

### Read only

The `isReadOnly` boolean prop makes the SearchField's text content immutable. Unlike `isDisabled`, the SearchField remains focusable
and the contents can still be copied. See [the MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly) for more information.

```tsx example
<SearchField label="Search" defaultValue="abc@adobe.com" isReadOnly />
```

### Label alignment and position

By default, the label is positioned above the SearchField. The `labelPosition` prop can be used to position the label to the side. The `labelAlign` prop can be used to align the label as "start" or "end". For left-to-right (LTR) languages, "start" refers to the left most edge of the SearchField and "end" refers to the right most edge. For right-to-left (RTL) languages, this is flipped.

```tsx example
<SearchField label="Search" labelPosition="side" labelAlign="end" />
```

### Help text
[View guidelines](https://spectrum.adobe.com/page/help-text/#Usage-guidelines)

Both a description and an error message can be supplied to a SearchField. The description is always visible unless the `validationState` is “invalid” and an error message is provided. The error message can be used to help the user fix their input quickly and should be specific to the detected error. All strings should be localized.

```tsx example
<Flex gap="size-100" wrap>
  <SearchField label="Search" defaultValue="Burritos" validationState="valid" description="Enter a query." />
  <SearchField label="Search" validationState="invalid" errorMessage="Empty input is not allowed." />
</Flex>
```

### Contextual help

A [ContextualHelp](ContextualHelp.html) element may be placed next to the label to provide additional information or help about a SearchField.

```tsx example
import {Content, ContextualHelp, Heading} from '@adobe/react-spectrum';

<SearchField
  label="Search"
  contextualHelp={
    <ContextualHelp variant="info">
      <Heading>Search tips</Heading>
      <Content>You can use modifiers like "date:" and "from:" to search by specific attributes.</Content>
    </ContextualHelp>
  } />
```

### Custom width

```tsx example
<SearchField label="Search" width="size-3600" />
```

### Custom icon
The icon in the SearchField can be changed to suit the theme of a search. For instance, if the SearchField was for searching users, an icon relating to that would help convey meaning. See the [Icons page](./workflow-icons.html) for more.
```tsx example
<SearchField label="Search for users" icon={<User />} />
```
